package handler

import (
	"errors"

	"github.com/kataras/iris/v12"
)

func CustomErrorResponseHandler(app *iris.Application) {
	app.OnErrorCode(iris.StatusNotFound, NotFoundErrorHandler)
	app.OnErrorCode(iris.StatusRequestTimeout, NotFoundErrorHandler)
	app.OnErrorCode(iris.StatusBadRequest, BadRequestErrorHandler)
	app.OnErrorCode(iris.StatusInternalServerError, InternalServerErrorHandler)
	app.OnErrorCode(iris.StatusMethodNotAllowed, MethodNotAllowedErrorHandler)
}

func ReturnErrorHandler(StatusCode int, ctx iris.Context) {
	if ctx.GetErr() == nil {
		ctx.SetErr(errors.New(iris.StatusText(StatusCode)))
	}
	ctx.JSON(iris.Map{"code": StatusCode, "message": ctx.GetErr().Error()})
	return
}

func NotFoundErrorHandler(ctx iris.Context) {
	ReturnErrorHandler(iris.StatusNotFound, ctx)
	return
}
func BadRequestErrorHandler(ctx iris.Context) {
	ReturnErrorHandler(iris.StatusBadRequest, ctx)
	return
}

func InternalServerErrorHandler(ctx iris.Context) {
	ReturnErrorHandler(iris.StatusInternalServerError, ctx)
	return
}

func MethodNotAllowedErrorHandler(ctx iris.Context) {
	ReturnErrorHandler(iris.StatusMethodNotAllowed, ctx)
	return
}
